package com.x.provider.customer.service.directory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.x.provider.customer.mapper.LevelDefMapper;
import com.x.provider.customer.model.domain.directory.LevelDef;
import com.x.provider.customer.model.query.directory.LevelDefQuery;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: liushenyi
 * @date: 2022/10/27/14:59
 */
@Service
public class LevelDefServiceImpl implements LevelDefService {

    private final LevelDefMapper levelDefMapper;

    public LevelDefServiceImpl(LevelDefMapper levelDefMapper){
        this.levelDefMapper = levelDefMapper;
    }

    @Override
    public Integer calcLevel(Integer levelType, Long exp) {
        final List<LevelDef> levelDefList = list(LevelDefQuery.builder().levelType(levelType).build());
        Integer result = 0;
        for (LevelDef levelDef : levelDefList){
            if (exp >= levelDef.getExp() && result < levelDef.getLevel()){
                result = levelDef.getLevel();
            }
            else{
                break;
            }
        }
        return result;
    }

    public List<LevelDef> list(LevelDefQuery levelDefQuery){
        return levelDefMapper.selectList(build(levelDefQuery).orderByAsc(LevelDef::getLevel));
    }

    private LambdaQueryWrapper<LevelDef> build(LevelDefQuery query){
        LambdaQueryWrapper<LevelDef> queryWrapper = new LambdaQueryWrapper<>();
        if (query.getLevelType() != null){
            queryWrapper = queryWrapper.eq(LevelDef::getLevelType, query.getLevelType());
        }
        return queryWrapper;
    }
}
